<template>
  <van-icon
    :color="isCollected ? '#ffa500':'#777'"
    :name="isCollected ? 'star':'star-o'"
    :loading="collectLoading"
    @click="onCollect"
  />
</template>

<script>
import { addCollectAPI, deleteCollectAPI } from '../../../api/index.js'

export default {
  name: 'CollectArticle',
  props: {
    isCollected: {
      type: Boolean,
      default: false
    },
    articleId: {
      type: String,
      default: ''
    }
  },
  data () {
    return {
      collectLoading: false // 关注文章收藏状态
    }
  },
  methods: {
    async onCollect () {
      // 定义一个提升变量 - 为什么创建在try外面
      let massage = '操作成功'
      try {
        // 调用接口前开始加载
        this.collectLoading = true
        if (this.isCollected) {
          // 已关注 需要取关
          await deleteCollectAPI(this.articleId)
          massage = '取消收藏成功'
        } else {
          // 未关注 需要关注
          await addCollectAPI({
            target: this.articleId
          })
          massage = '收藏成功'
        }

        // .sync的方式实现子父组件传参
        this.$emit('update:isCollected', !this.isCollected)
        this.$toast.success(massage)
      } catch (err) {
        this.$toast.fail('网络异常，请稍后重试')
        console.log(err)
        this.$toast.fail(massage)
      }
      // 无论是成功还是失败都需要关闭加载状态
      this.collectLoading = false
    }
  }
}
</script>

<style scoped>

</style>
